import cStringIO
import os.path
import zipfile

class PK3:
  def __init__(self, filename):
    self.zip = zipfile.ZipFile(filename, 'r')
    self.namelist = self.zip.namelist()
    self.namelist.sort(cmp)
    self.namelist = [(name, os.path.normpath(name)) for name in self.namelist]

  def exists(self, filename):
    filename = os.path.normpath(filename)
    for name, normalized_name in self.namelist:
      if normalized_name == filename:
        return True
    return False

  def filenames(self, prefix=None):
    if prefix:
      prefix = os.path.normpath(prefix)
    return [normalized_name for name, normalized_name in self.namelist if not prefix or normalized_name.startswith(prefix)]

  def open(self, filename):
    filename = os.path.normpath(filename)
    for name, normalized_name in self.namelist:
      if normalized_name == filename:
        return cStringIO.StringIO(self.zip.read(name))
    raise IOError
